from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView
from rest_framework.generics import RetrieveAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import UpdateAPIView
from rest_framework import status

from .serializers import UserCreateSerializer
from .serializers import UserDetailSerializer
from .models import User
from .serializers import EmailSerializer
from rest_framework.permissions import IsAuthenticated


# 验证用户名是否存在，返回用户名和个数

class UsernameCountView(APIView):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        print(count)
        return Response({
            'username': username,
            'count': count
        })


# 验证手机是否存在，


class MobileCountView(APIView):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return Response({
            'username': mobile,
            'count': count
        })


# 创建视图，并调用序列化器，个人中心的个人设置
class UserView(CreateAPIView):
    #     创建序列器，并调用
    serializer_class = UserCreateSerializer


class UserDetailView(RetrieveAPIView):
    """
    用户详情
    """
    serializer_class = UserDetailSerializer
    # 认证登录帐号的
    permission_classes = [IsAuthenticated]
# 重写get_object,不根据主键查询，返回ｕｓｅｒ用户
    def get_object(self):
        return self.request.user

class EmailView(UpdateAPIView):
    """
    保存用户邮箱
    """
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    def get_object(self, *args, **kwargs):
        print(
            "111111111"
        )
        return self.request.user
# 邮箱验证
from rest_framework import status


class VerifyEmailView(APIView):
    """
    邮箱验证
    """
    def get(self, request):
        # 获取token
        token = request.query_params.get('token')
        print(token)
        print('1')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证token
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = True
            user.save()
            return Response({'message': 'OK'})